import { useEffect, useState, useCallback } from 'react';
import { SwapOutlined } from '@ant-design/icons';
import { message, Popover, Select } from 'antd';
import { Button, Pagination, Row, Col, Modal, Input, Spin } from 'antd';
import dayjs from 'dayjs';
import debounce from 'lodash.debounce';
import api from '@/api/account';
import CustomizeHeader from '@/components/customizeHeader/customizeHeader';
import { useNavigate } from 'react-router-dom';
// import UserEvent from '@/components/userEvent';
import FilterModal from '@/components/filterModal';
import { scoreResultList, scoreResult } from '@/api/scoreResult';

import './index.scss';
const { TextArea } = Input;
const User = props => {
    const [accountModal, setAccountModal] = useState({ userId: '', open: false, isDelete: false });
    const [filterVisible, setFilterVisible] = useState(false);
    const [isEditFlag, setEditFlag] = useState(true);
    // 页面的Loading状态
    const [loading, setLoading] = useState(false);
    // 确认按钮的loading状态
    const [confirmLoading, setConfirmLoading] = useState(false);
    // 当前点击的左侧的对象
    const [currentLeft, setCurrentLeft] = useState<{
        scoreTitle: string;
        scoreId: string;
        active: boolean;
        scoreSummary: string;
        textValue: string;
    }>({
        scoreTitle: '',
        scoreId: '',
        active: true,
        scoreSummary: '',
        textValue: '',
    });
    const editChange = () => {
        const flag = !isEditFlag;
        // 将问题列表的输入框设置为禁用，不是edit的时候就禁用
        const updatedList = questionList.map(item => {
            return { ...item, disabled: !flag };
        });
        setQuestionList(updatedList);
        setEditFlag(flag);
    };
    /**
     * 调用接口，获取右边数据
     * @param eqSkillType 是调用getQuestionType这个方法传过来的参数
     */
    const getScoreList = async () => {
        const params = {};
        setLoading(true);
        scoreResultList(params).then((res: any) => {
            setLoading(false);
            if (res && res.length > 0) {
                let currentIndex = 0;
                const data = res.map((item: any, index: number) => {
                    if (item.scoreId == currentLeft.scoreId) {
                        currentIndex = index;
                    }
                    return {
                        ...item,
                        active: currentIndex == index ? true : false,
                    };
                });
                setCurrentLeft({ ...data[currentIndex], textValue: data[currentIndex].scoreSummary });
                setLeftTitle(data);
            } else {
                setLeftTitle([]);
            }
        });
    };
    useEffect(() => {
        // 一进来，默认调用接口
        getScoreList();
    }, []);
    /**
     * 调用接口，保存数据
     * @param eqSkillType
     */
    const confirmChange = async () => {
        setConfirmLoading(true);
        const params = {
            scoreId: currentLeft.scoreId,
            scoreSummary: currentLeft.textValue,
        };
        scoreResult(params).then((res: any) => {
            getScoreList();
            setConfirmLoading(false);
            // 调用此方法是将状态设置为不是编辑的状态
            editChange();
        });
    };
    const questionListDefault = [
        {
            question: 'Test Question1',
            index: 0,
            questionTextValue: '1',
            placeholder: 'Enter the test question 1',
            disabled: true,
        },
        {
            question: 'Test Question2',
            index: 1,
            questionTextValue: '1',
            placeholder: 'Enter the test question 2',
            disabled: true,
        },
        {
            question: 'Test Question',
            index: 2,
            questionTextValue: '1',
            placeholder: 'Enter the test question 3',
            disabled: true,
        },
        {
            question: 'Test Question4',
            index: 3,
            questionTextValue: '1',
            placeholder: 'Enter the test question 4',
            disabled: true,
        },
        {
            question: 'Test Question5',
            index: 4,
            questionTextValue: '1',
            placeholder: 'Enter the test question 5',
            disabled: true,
        },
    ];
    const [questionList, setQuestionList] = useState<
        {
            question: string;
            index: number;
            questionTextValue: string;
            placeholder: string;
            disabled: boolean;
        }[]
    >(questionListDefault);
    const changeTextValue = (value: string) => {
        const obj = { ...currentLeft, textValue: value };
        setCurrentLeft(obj);
    };
    // 题目列表以及题目切换
    // const leftListDefault = [
    //     {
    //         scoreTitle: '0-25%',
    //         scoreId: '',
    //         active: true,
    //     },
    // ];
    const [leftTitle, setLeftTitle] = useState<
        {
            scoreTitle: string;
            scoreId: string;
            active: boolean;
            scoreSummary: string;
        }[]
    >([]);
    const clickItem = (item: { scoreTitle: string; scoreId: string; active: boolean; scoreSummary: string }) => {
        console.log(item, '点击的对象');
        setCurrentLeft({ ...item, textValue: item.scoreSummary });
        // 创建一个新的数组updatedList，如果是直接使用原数组questionList，就会导致react没有检测到数组改变就会导致页面不更新
        const updatedList = leftTitle.map(everyOne => {
            if (everyOne.scoreId === item.scoreId) {
                return { ...everyOne, active: true };
            } else {
                return { ...everyOne, active: false };
            }
        });
        setLeftTitle(updatedList);
    };
    return (
        <>
            <div className="page-main account scoreResultBox">
                <div className="container">
                    <div className="search-bar">
                        <div className="page-title">Score results</div>
                    </div>
                    <div>
                        <Row gutter={30}>
                            <Col span={2}>
                                <div className="leftContent">
                                    {loading ? (
                                        <div className="flex-center leftLoadingBox">
                                            <Spin tip="Loading" />
                                        </div>
                                    ) : (
                                        leftTitle.map((item, index) => {
                                            return (
                                                <div
                                                    key={index}
                                                    className={item.active ? 'leftItemBox active' : 'leftItemBox'}
                                                    onClick={() => clickItem(item)}
                                                >
                                                    {item.scoreTitle}
                                                </div>
                                            );
                                        })
                                    )}
                                </div>
                            </Col>
                            <Col span={22}>
                                <div className="rightContent">
                                    <div>
                                        <div className="rightTitle">Score segment summary</div>
                                        <div className="textAreaContent">
                                            <TextArea
                                                value={currentLeft.textValue}
                                                onChange={e => changeTextValue(e.target.value)}
                                                autoSize={{ minRows: 25, maxRows: 25 }}
                                                disabled={isEditFlag}
                                                placeholder="Enter the score segment summary"
                                            />
                                        </div>
                                    </div>
                                    <div>
                                        <div className="flex-end footerBox">
                                            {isEditFlag ? (
                                                <Button
                                                    className="orangeBtn ml-10"
                                                    type="primary"
                                                    htmlType="submit"
                                                    onClick={() => editChange()}
                                                >
                                                    Edit
                                                </Button>
                                            ) : (
                                                <div className="flex-end">
                                                    <div className="grayBtn" onClick={() => editChange()}>
                                                        <div>Cancel</div>
                                                    </div>
                                                    <Button
                                                        className="orangeBtn ml-10"
                                                        type="primary"
                                                        htmlType="submit"
                                                        disabled={confirmLoading}
                                                        loading={confirmLoading}
                                                        onClick={() => confirmChange()}
                                                    >
                                                        Save
                                                    </Button>
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                </div>
                            </Col>
                        </Row>
                    </div>
                </div>
            </div>
            {/* <UserEvent
                params={accountModal}
                onCancel={() => setAccountModal({ userId: '', open: false, isDelete: false })}
            /> */}
            <FilterModal
                open={filterVisible}
                onCancel={(isSearch: boolean) => {
                    setFilterVisible(false);
                    console.log(isSearch);
                }}
            />
        </>
    );
};

export default User;
